<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/3/16 0016
 * Time: 17:27
 */
namespace app\admin\controller;
use app\models\Models;

class Voucher extends Check{
    /**
     * 代金券列表
     * @return \think\response\View
     */
    public function voucherList(){
        $get = input('param.');
        $voucher = new Models('voucher');
        $type = new Models('voucherType');
        // 条件查询
        $search = search($get,'a.voucher_no','a.begin_time','a.status');
        $where  = $search['condition'];
        if($get['type_id'] != ''){
            $where .= ' and a.type_id = '.$get['type_id'];
            $search['display']['type_id'] = $get['type_id'];
        }
        $join   = [
            ['voucher_type b','a.type_id = b.id','left'],
            ['business c','a.bid = c.id','left'],
        ];
        $field  = "a.*,b.name,c.name business";
        $list = $voucher->_page($where,$field,'a.id desc',$join,$get['page'],15,$get);
        $type = $type->_select();
        return view('voucherList',['list'=>$list->items(),'page'=>$list->render(),'display'=>$search['display'],'type'=>$type]);
    }

    /**
     * 添加代金券
     * @return array|\think\response\View
     */
    public function voucherAdd(){
        if(request()->isAjax()){
            $post = input('param.');
            $voucher = new Models('voucher');
            try{
                $post['begin_time']  = strtotime($post['begin_time']);
                $post['end_time']    = strtotime(date('Y-m-d',strtotime($post['end_time'].'+1 day'))) - 1;
                $post['create_time'] = time();
                $post['voucher_no'] = date('YmdHis').rand(0001,9999);
                $uid  = $voucher->_add($post);
                if(!$uid){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $type  = new Models('voucherType');
        $admin = new Models('admin');
        // 用户类型列表
        $type = $type->_select(['status'=>Models::STATUS_ON]);
        // 商家列表
        $business  = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON,'b.id'=>['<>',Models::OFFICIAL]],'a.id,b.name');
        return view('voucherAdd',['type'=>$type,'business'=>$business]);
    }

    /**
     * 修改代金券
     * @return array|\think\response\View
     */
    public function voucherSave(){
        $user = new Models('user');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                // 添加场景验证
                $validate = $this->validate($post,'User.userSave');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                $bool = $user->_save($post);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $voucher = new Models('voucher');
        $info  = $voucher->_find($get['id']);
        $type  = new Models('voucherType');
        $admin = new Models('admin');
        // 用户类型列表
        $type = $type->_select(['status'=>Models::STATUS_ON]);
        // 商家列表
        $business  = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON,'b.id'=>['<>',Models::OFFICIAL]],'a.id,b.name');
        return view('voucherSave',['type'=>$type,'info'=>$info,'business'=>$business]);
    }

    /**
     * 发行
     * @return array
     */
    public function issue(){
        $voucher = new Models('voucher');
        if(request()->isAjax()){
            $post  = input('param.');
            $user  = new Models('user');
            $issue = new Models('voucherIssue');
            $time = time();
            try{
                $where = [];
                // 指定条件
                if($post['where'] == 1){
                    if($post['recharge_begin'] >= $post['recharge_end']){
                        throw new \LogicException('格式错误',1010);
                    }
                    $begin = empty($post['recharge_begin']) ? 0 : $post['recharge_begin'];
                    $recharge = $begin.','.$post['recharge_end'];
                    $where = ['b.recharge'=>['in',$recharge]];
                }
                // 指定单个用户
                if($post['where'] == 2){
                    $info = $user->_find(['id'=>$post['uid']]);
                    if(!$info){
                        throw new \LogicException('用户不存在',1010);
                    }
                    $where = ['a.id'=>$post['uid']];
                }
                // 指定商家粉丝
                if($post['where'] == 3){
                    $business_ids = implode(',',$post['business_id']);
                    $follow = new Models('follow');
                    $ids = $follow->getColumn(['status'=>Models::FOLLOW_YES,'follow_object'=>Models::FOLLOW_BUSINESS,'follow_id'=>['in',$business_ids]],'fans_id');
                    if($ids){
                        $ids = array_unique($ids);
                        $ids = implode(',',$ids);
                        $where = ['a.id'=>['in',$ids]];
                    }
                }
                $ids = $user->joinManyColumn([['account b','a.id = b.uid','left']],$where,'a.id','a.id asc');
                if($ids) {
                    $qty = count($ids);   // 计算发行数量
                    // 组合数组
                    foreach ($ids as $k=>$v) {
                        $vouc['uid'] = $v;
                        $vouc['voucher_id'] = $post['id'];
                        $vouc['create_time'] = $time;
                        $add[] = $vouc;
                    }
                    // 批量插入获得代金券的用户记录
                    $bool1 = $issue->_addAll($add);
                    if(!$bool1) {
                        throw new \LogicException('操作失败', 1010);
                    }
                    // 更新对应代金券信息
                    $bool = $voucher->_save(['id' => $post['id'], 'status' => Models::VOUCHER_ISSUE_YES, 'send_num' => $qty]);
                    if(!$bool) {
                        throw new \LogicException('操作失败', 1010);
                    }
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get  = input('param.');
        $info = $voucher->_find(['id'=>$get['id']]);
        $admin = new Models('admin');
        // 商家列表
        $business  = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON,'b.id'=>['<>',Models::OFFICIAL]],'a.id,b.name');
        return view('issue',['info'=>$info,'list'=>$business]);
    }
}